package com.lepai.web.interception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.Charset;

/**
 * @author weihaolong
 * @date 2018-10-19 10:44
 */
public class MyRequestWrapper extends HttpServletRequestWrapper {

    private final Logger log = LoggerFactory.getLogger(MyRequestWrapper.class);
    private final byte[] body;

    public MyRequestWrapper(HttpServletRequest request){
        super(request);
        String sessionStream = getBodyString(request);
        log.info("RequestToJson body:" + sessionStream);
        body = sessionStream.getBytes(Charset.forName("UTF-8"));
    }


    @Override
    public ServletInputStream getInputStream(){
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        ServletInputStream servletInputStream = new ServletInputStream() {
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }

            @Override
            public boolean isFinished() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public boolean isReady() {
                // TODO Auto-generated method stub
                return false;
            }

            @Override
            public void setReadListener(ReadListener listener) {
                // TODO Auto-generated method stub

            }
        };
        return servletInputStream;
    }

    //返回自己的inputStream
    @Override
    public BufferedReader getReader(){
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    /**
     * 复制input输入流
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public InputStream cloneInputStream(ServletInputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            while ((len = inputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            byteArrayOutputStream.flush();
        } catch (IOException e) {
            log.info("clone servletInputStream failed", e);
            throw e;
        }
        InputStream byInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        return byInputStream;
    }

    //获取request中的getInputStream,返回String字段
    public static String getBodyString(HttpServletRequest request) {
        BufferedReader br;
        StringBuilder sb = null;
        String reqBody = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
            String line = null;
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
            reqBody = reqBody.substring(reqBody.indexOf("{"));
            request.setAttribute("inputParam", reqBody);
            System.out.println("JsonReq reqBody>>>>>" + reqBody);
            return reqBody;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "jsonerror";
        }
    }
}
